/**
 * 详情对话框
 */
var BinsInfoDlg = {
    data: {
        name:""
        ,area:""
        ,address:""
        ,gpsInfo:""
        ,status:""
        ,wasteTypes:""
        ,manageUserId:""
        ,qrcodeUrl:""
        ,qrcodeTicket:""
        ,qrcodeImg:""
        ,createTime:""
        ,useTime:""
        ,statusDesc:""
        ,lastUpdateTime:""
    }
};
var areaNames="";

layui.use(['form', 'ax','laydate','admin','upload','yutons_sug','citypicker'], function () {
    var $ = layui.jquery;
    var $ax = layui.ax;
    var form = layui.form;
    var yutonsMods = layui.yutons_sug;
    var cityPicker = layui.citypicker;
    var admin = layui.admin;

    // 让当前iframe弹层高度适应
    admin.iframeAuto();
    

    //获取详情信息，填充表单
    var ajax = new $ax(Feng.ctxPath + "/bins/detail/" + Feng.getUrlParam("id"));
    var result = ajax.start();
    var wasteTypes = result.data.wasteTypes;
    var wasteTypeArr = wasteTypes.split(",");
    for(var i=0;i<wasteTypeArr.length;i++){
        if($.trim(wasteTypeArr[i])!=""){
            $("#"+wasteTypeArr[i]).attr("checked",true);
        }

    }
    var statusDesc = result.data.statusDesc;
    if(statusDesc) {
        var statusDescSplit = statusDesc.split(",");
        var xsTimeRange = statusDescSplit[0].split("-");
        $("#xsBeginTime").val(xsTimeRange[0]);
        $("#xsEndTime").val(xsTimeRange[1]);
        $("#xsTime").val(statusDescSplit[1]);
        $("#xsTimeGap").val(statusDescSplit[2]);
    }
    var currentPicker = new cityPicker("#area", {
        provincename:"广东省",
        cityname:"东莞市",
        districtname: "寮步镇",
        level: '3',// 级别
    });
    var areaData = result.data.area;
    var areaDatas = areaData.split(",");
    console.log("区域："+areaDatas[0]+","+areaDatas.length);
    currentPicker.setValue(areaDatas[0]);
    if(areaDatas.length>1){
        $("#areaNext").val(areaDatas[1]);
    }

    //areaNames = result.data.area;
    form.val('binsForm', result.data);
    $("#area").val(areaDatas[0]);
    if(areaDatas.length>1){
        $("#areaNext").html("<option value='"+areaDatas[1]+"'>"+areaDatas[1]+"</option>");
        form.render("select");
    }
    $("#useTime").val(result.data.useTime.substring(0,10));



    //表单提交事件
    form.on('submit(btnSubmit)', function (data) {
        console.table(data);
        var validation = new Validation($("#binsForm")[0], {onSubmit:false});
        var validate = validation.validate();
        if(validate){
            var ajax = new $ax(Feng.ctxPath + "/bins/editItem", function (data) {
                if(data.success) {
                    Feng.success("更新成功！");
                    //传给上个页面，刷新table用
                    admin.putTempData('formOk', true);
                    //关掉对话框
                    admin.closeThisDialog();
                }else{
                    Feng.error(data.message);
                }


            }, function (data) {
                Feng.error("更新失败！" + data.responseJSON.message)
            });
            var wasteTypes = $("#wasteTypes").val();
            wasteTypes = wasteTypes.replace(/,+/gi,",");
            $("#wasteTypes").val(wasteTypes);
            var value = $("#xsBeginTime").val()+"-"+$("#xsEndTime").val()+","+$("#xsTime").val()+","+$("#xsTimeGap").val();
            $("#statusDesc").val(value);
            console.log("定时时间："+value);
            console.table(data.field);
            ajax.set(data.field);
            var chooseFiles = $(".layui-upload-choose");
            if(chooseFiles.length>0){
                imagePathUploader.upload();
            }else{
                ajax.start();
            }

        }else{
            var serializeArray = $(".validation-failed");
            var errMsgs = "";
            for(var i=0;i<serializeArray.length;i++){
                var elemInfo = serializeArray[i];
                var elem = $("#"+elemInfo.name)[0];
                if(elem && elem.tooltip){
                    errMsgs+="<div><span style='color:dodgerblue'>"+elem.placeholder+"输入框有误：</span><span style='color:red'>"+elem.tooltip.content+"</span></div>"
                    var tipElem = elem.tagName=="SELECT"?$(elem).next():elem;
                    layer.tips(elem.tooltip.content,tipElem,{
                        tips: [1, '#FF99CC'],
                        time: 4000,
                        tipsMore: true
                    });
                }
            }
            //Feng.error(errMsgs);
        }
        return false;

    });

    form.on("checkbox",function(data){
        console.log(data.elem.checked);
        var wasteTypes = $("#wasteTypes").val();
        if(data.elem.checked){
            console.log(data.value);
            $("#wasteTypes").val(wasteTypes+data.value+",");
            console.log(BinsInfoDlg.data.wasteTypes);
        }else{
            $("#wasteTypes").val(wasteTypes.replace(data.value,""));
        }

    });

    /*yutonsMods.render({
        id: "area", //设置容器唯一id
        height: "167",
        cols: [
            [{
                field: 'name',
                title: '区域名称'
            }]
        ], //设置表头
        params: [
            {
                name: 'area',
                field: 'name'
            }],//设置字段映射，适用于输入一个字段，回显多个字段
        type: 'sugTable', //设置输入框提示类型：sug-下拉框，sugTable-下拉表格
        url: Feng.ctxPath + "/region/search?params=" //设置异步数据接口,url为必填项,params为字段名
    });*/
    var areaNextChange = function(){
        var curAreaName = $("#area").val();
        if(curAreaName!=areaNames){


            var that = $("#areaNext")[0];
            $.getJSON(Feng.ctxPath+"/region/search?params="+$("#area").val()+"&r="+Math.random(),function(areaNameList){
                $(that).empty();
                for(var i=0;i<areaNameList.length;i++){
                    $(that).html($(that).html()+"<option name='"+areaNameList[i]+"'>"+areaNameList[i]+"</option>");
                }
                form.render("select");
                $("#areaNext").parent().find(":text").click(function(){
                    areaNextChange();
                })
            });
            areaNames = curAreaName;
        }
    }
    $("#areaNext").parent().find(":text").click(function(){
        areaNextChange();
    })
    //返回按钮
    $("#backupPage").click(function () {
        window.location.href = Feng.ctxPath + "/bins";
    });
    var laydate = layui.laydate;
    lay('.datetime-input').each(function(){
        laydate.render({
            elem: this
            ,trigger: 'click'
            ,type: 'date'
        });
    });
    lay('.date-input').each(function(){
        laydate.render({
            elem: this
            ,format:"HH"
            ,trigger: 'click'
            ,type: 'time'
        });
    });
});